package util;
import java.util.ArrayList;

import struct.Function;
import struct.Identity;
import struct.Rule;
import struct.Unifier;

public class Utils {
    public static Unifier betterWork;
    
    public static ArrayList<Rule> renameRules(ArrayList<Rule> rules)
    {
        int max = 0;
        for (int i = 0; i < rules.size(); i++)
        {
            int m1 = rules.get(i).getLeft().getMaxIndex();
            int m2 = rules.get(i).getRight().getMaxIndex();
            
            m1 = m1 > m2 ? m1 : m2;
            if (max < m1)
            {
                max = m1;
            }
        }
        betterWork.setMax(max);
        
        ArrayList<Rule> renamed = new ArrayList<Rule>(rules.size());
        for (int i = 0; i < rules.size(); i++)
        {
            renamed.add((Rule)rules.get(i).clone());
            renamed.get(i).getLeft().setIndex(max + 1);
            renamed.get(i).getRight().setIndex(max + 1);
        }
        
        return renamed;
    }
    
    public static ArrayList<Function> getFunx(Rule rule)
    {
        ArrayList<Function> ret = new ArrayList<Function>();
        if (rule != null)
        {
            Function func;
            if (rule.getLeft().getTerm() instanceof Function)
            {
                func = (Function) rule.getLeft().getTerm();
                ArrayList<Function> temp = func.getFunx();
                for (int t = 0; t < temp.size(); t++)
                {
                    if (!ret.contains(temp.get(t)))
                    {
                        ret.add(temp.get(t));
                    }
                }
            }
        }
        return ret;
    }
    
    public static Identity substitute(Identity oldi, Identity newi, Identity in)
    {
        Identity ret = (Identity) in.clone();
        if (ret.toString().contains(oldi.toString()))
        {
            if (ret.equals(oldi))
            {
                ret = newi;
            } else
            if (ret instanceof Function)
            {
                Function func = (Function) ret;
                for (int i = 0; i < func.getArgs().length; i++)
                {
                    func.setArg(substitute(oldi, newi, func.getArg(i)), i);
                }
                ret = func;
            }
        }
        return ret;
    }
}
